package com.mlnx.bluwifi.manager;

import com.alibaba.fastjson.JSONObject;
import com.mlnx.bluwifi.pojo.DataCache;
import com.mlnx.bluwifi.pojo.dto.Connect;
import com.mlnx.bluwifi.pojo.dto.ConnectBlu;
import com.mlnx.bluwifi.service.WifiBluService;
import com.mlnx.bluwifi.utils.HttpUtil;
import com.mlnx.bluwifi.utils.SpolanyaUtils;
import com.mlnx.common.utils.MyLog;
import com.mlnx.device.entity.Device;
import com.mlnx.device.entity.LanyaDevice;
import com.mlnx.device.enums.DeviceType;
import com.mlnx.device.service.LanyaDeviceService;
import org.shan.spring.rest.RestUtils;

import java.util.*;

/**
 * Created by amanda.shan on 2019/11/18.
 */
public class AskSpoOnlineTask extends TimerTask {

    MyLog log = MyLog.getLog(getClass());

    private LanyaDeviceService lanyaDeviceService;

    private WifiBluService wifiBluService;

    public AskSpoOnlineTask(LanyaDeviceService lanyaDeviceService, WifiBluService wifiBluService) {
        this.lanyaDeviceService = lanyaDeviceService;
        this.wifiBluService = wifiBluService;
    }

    @Override
    public void run() {

        List<LanyaDevice> list = lanyaDeviceService.list();

        Set<String> connectedSpo = new HashSet<>();

        for (LanyaDevice lanyaDevice : list) {
            if(lanyaDevice.getStartUsing()==0){
                String str = "";
                int size = 0;
                try {
                    str = HttpUtil.sendGet(SpolanyaUtils.getConnectDevice(lanyaDevice.getIpAddress()), "connection_state" +
                            "=connected&mac=" + lanyaDevice.getMac() + "&access_token=");
                    Connect connect = JSONObject.parseObject(str, Connect.class);
                    if (connect == null) {
                        if(lanyaDevice.getState()==1){
                            lanyaDevice.setState(0);
                            lanyaDeviceService.updateById(lanyaDevice);
                        }

                        log.debug("Ap无法连接，解析数据为空:{}", lanyaDevice);
                    } else {
                        if(lanyaDevice.getState()==0){
                            lanyaDevice.setState(1);
                            lanyaDeviceService.updateById(lanyaDevice);
                        }
                        List<ConnectBlu> nodes = connect.getNodes();
                        if (nodes != null && nodes.size() > 0) {
                            for (ConnectBlu connectBlu : nodes) {
                                if (connectBlu.getId() != null) {
                                    size++;
                                }
                            }

                            if (size == 0){
                                continue;
                            }else{
                                size = 0;
                            }

                            log.debug("================={}: 在线设备详情===================", lanyaDevice);
                            log.debug("扫描在线设备:{}", str);

                            for (ConnectBlu connectBlu : nodes) {
                                if (connectBlu.getId() != null) {
                                    String deviceId = connectBlu.getId();

                                    Device device = wifiBluService.getDevice(deviceId);
                                    DeviceType deviceTypeId = null;
                                    if (device != null) {
                                        deviceTypeId = device.getDeviceTypeId();
                                    }
                                    log.debug("{}AP设备已连接{}设备:{}", lanyaDevice.getMac(),
                                            deviceTypeId != null ? deviceTypeId.getMessage() : "未知设备", deviceId);
                                    size++;
                                    connectedSpo.add(deviceId);
                                    //检查数据未更新时间超过5 秒则掐断
                                    DataCache dataCache=SpoPolicy.getInstance().getDataCache(deviceId);
                                    if(dataCache.getCurrentTime() !=null && dataCache.getDeviceType().equals(DeviceType.SPO_DEVICE)){
                                        if ((System.currentTimeMillis() - dataCache.getCurrentTime()) > 5000){
                                            RestUtils.getRestTemplate().delete(SpolanyaUtils.delConnectUrl(deviceId,
                                                    lanyaDevice.getIpAddress()));
                                            log.info("超时接收血氧数据断开设备：{}", deviceId);
                                        }
                                    }
//
                                }
                            }
                            log.debug("================={}:设备总数{}===================", lanyaDevice, size);
                        }
                    }
                } catch (Exception e) {
                    log.error(e, "获取在线设备任务错误");
                }
            }

        }

        ConDeviceManage.getInstance().setConnectedSpo(connectedSpo);

    }

    public void start() {
        new Timer().schedule(this, 0, 5000);
    }
}
